package file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.Base64;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Test;

public class StorageFile {

	protected String fileName;
	protected File file;
	protected RandomAccessFile randomAccessFile;
	protected PrintWriter writer;
	protected FileChannel cursorChannel;
	
	public StorageFile(String fileName) throws IOException {
		this.fileName = fileName;
		file = new File(fileName);
		boolean isNew = false;
		if(!file.exists()){
			file.createNewFile();
			isNew = true;
		}
		writer = new PrintWriter(new FileOutputStream(file, true));
		if(isNew){
			writer.println(-1);
		}
		
		randomAccessFile = new RandomAccessFile(file, "rw");
		cursorChannel = randomAccessFile.getChannel();
	}
	
	public void append(String data){
		writer.println(Base64.getEncoder().encodeToString(data.getBytes()));
		writer.flush();
	}
	
	public synchronized String readItem() throws IOException{
		//获取浮标
		long pos = randomAccessFile.getFilePointer();
		randomAccessFile.seek(0);
		long cursor = randomAccessFile.readLong();
		if(cursor > 0){
			randomAccessFile.seek(cursor);
		}else{
			randomAccessFile.readLine();
		}
		
		String str = randomAccessFile.readLine();
		
		//设置浮标
		pos = randomAccessFile.getFilePointer();
		randomAccessFile.seek(0);
		randomAccessFile.writeLong(pos);
		randomAccessFile.seek(pos);
		return str == null ? null : new String(Base64.getDecoder().decode(str.getBytes()));
	}
	
	public static void main(String[] args) throws IOException {
		
		final StorageFile file = new StorageFile("test.txt");
//		for(int i = 0; i < 100; i++){
//			file.append(String.valueOf(i));
//		}
		ExecutorService thread = Executors.newFixedThreadPool(8);
//			final int index = i;
//			thread.execute(()->{
//				file.append(String.valueOf(1111111 * index));
//			});
//		}
		
		for(int i = 1; i <= 8; i++){
			thread.execute(()->{
				try {
					String line = file.readItem();
					while(line != null){
						System.out.println(line);
						line = file.readItem();
						System.out.println();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			});
		}
	}
}
